﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Jb.Common.Extensions;
using Jb.Domain;
using Jb.Web.ViewModels;
using Jb.Web.Utility;
using AutoMapper;
using Jb.Web.ViewModels.UtilityModels;

namespace Jb.Web.Controllers
{
    public class CompanyController : BaseController
    {
		private JbEntities _Context = new JbEntities();
        
		#region Constructors
		public CompanyController()
		{
		}

		public CompanyController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return View("List", BuildCompanyList());            
        }

        public ActionResult List()
        {
            return View(BuildCompanyList());
        }

		/// <summary>
        /// This is the Company Home page at JobBoard
        /// </summary>
        /// <param name="pageNo"></param>
        /// <returns></returns>
        public ActionResult Details(String companyKey, String pageNo = null)
        {
            Company company = _Context.Companies.Include("IndustryType").Include("Address").Include("Address.City").FirstOrDefault(P => String.Compare(P.Url, companyKey, true) == 0);
            if (company != null)
            {
                PagerConfig pager = new PagerConfig(pageNo.ToInt() > 0 ? pageNo.ToInt() : 1, ConfigReader.PageSizeOfCompanyJobList, 0);
                UtilityDAO dao = new UtilityDAO();
                Jb.Domain.DbParameter[] parameters = new[]{
                    new Jb.Domain.DbParameter("@CompanyID", company.ID),
                    new Jb.Domain.DbParameter("@GetPublishedOnly", 1)
                };
                int totalRecord = 0;
                DataSet ds = dao.GetPagedData(DbObject.SP.GET_PAGED_JOB_LIST_BY_COMPANY, parameters, pager.PageNo, pager.PageSize, out totalRecord, true);
                pager.TotalRecord = totalRecord;
                ListConfig listConfig = new ListConfig(ds.Tables[0], pager);
                ViewData[AppConstants.ViewDataKeys.GENERIC_KEY] = listConfig;
                ViewData[AppConstants.ViewDataKeys.COMPANY_KEY] = companyKey;
            }
            return View(company);
        }

        /// <summary>
        /// Activates a newly registered Company account and its users through
        /// An Activation link privided in the registration success email.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public ActionResult Activate(String id, String key)
        {
            if (id.IsNullOrEmpty() && key.IsNullOrEmpty())
                ModelState.AddModelError(AppConstants.Validation.WRONG_ACTIVATION_REQUEST, "Invalid Request.");
            else
            {
                Guid activationKey = Guid.Empty;
                Guid.TryParse(key, out activationKey);
                int companyID = id.ToInt();
                Company company = _Context.Companies.FirstOrDefault(P => P.ActivationKey == activationKey && P.ID == companyID);
                if (company == null)
                    ModelState.AddModelError(AppConstants.Validation.WRONG_ACTIVATION_REQUEST, "Invalid Request.");
                else
                {
                    if (company.IsActive)
                        ModelState.AddModelError(AppConstants.Validation.WRONG_ACTIVATION_REQUEST, "This company is already activated.");
                    else
                    {
                        company.IsActive = true;
                        foreach (Contact contact in company.Contacts)
                        {
                            contact.IsActive = true;
                        }
                        var users = from P in _Context.Users where P.Contact.CompanyID == company.ID select P;
                        foreach (User user in users)
                        {
                            user.IsActive = true;
                        }
                        ///Auto subscription to a free package if enabled in site configuration
                        if (SiteConfigReader.AutoSubscribeToFreePackage)
                            SubscribeToFreePackage(company);

                        _Context.SaveChanges();
                        ViewData[AppConstants.ViewDataKeys.HAS_ACTIVATED] = true;
                    }
                }
            }
            return View();
        }
				
		#endregion Action Methods
		
		#region Helper Methods

		/// <summary>
        /// Builds a ListConfig object with a list of Company
        /// </summary>
        /// <returns></returns>
        private List<CompanyViewModel> BuildCompanyList()
        {
            var query = from P in _Context.Companies.Include("Address.City.State.Country") where P.IsActive orderby P.Name select P;
            List<CompanyViewModel> companies = Mapper.Map<List<Company>, List<CompanyViewModel>>(query.ToList());
            //companies = null;
            return companies;
        }

        /// <summary>
        /// Subscribes a Company to a Free package
        /// </summary>
        /// <param name="company"></param>
        private void SubscribeToFreePackage(Domain.Company company)
        {
            Package package = _Context.Packages.FirstOrDefault(P => P.Price <= 0 && P.IsActive);
            if (package != null)
            {
                PackageSubscription subscription = new PackageSubscription();
                subscription.CompanyID = company.ID;
                subscription.PackageID = package.ID;
                subscription.Duration = package.Duration;
                subscription.MaxJobPost = package.MaxJobPost;
                subscription.MaxResumeDownload = package.MaxResumeDownload;
                subscription.SubscribedOn = DateTime.Now;
                subscription.IsActive = true;
                subscription.RefSalesOrderID = null;

                _Context.AddToPackageSubscriptions(subscription);
                //_Context.SaveChanges();
            }
        }

        #endregion			
    }
}


